package ute.mvc.controller.home;

import javax.servlet.ServletRequest;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import ute.mvc.model.User;
import ute.mvc.model.User.GroupReset;
import ute.mvc.service.UserService;
import ute.mvc.util.GMailUtil;
import ute.mvc.util.PasswordUtil;

@Controller
@RequestMapping(value = "/reset")
public class ResetPasswordController {

	@Autowired
	ReCaptchaImpl reCaptcha;
	@Autowired
	UserService userService;

	@RequestMapping(method = RequestMethod.GET)
	public String getResetPassword(Model model) {

		model.addAttribute("user", new User());
		return "reset";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String setResetPassword(
			@Validated(GroupReset.class) @ModelAttribute User user,
			BindingResult result, ModelMap model,
			@RequestParam("recaptcha_challenge_field") String challangeField,
			@RequestParam("recaptcha_response_field") String responseField,
			ServletRequest servletRequest) {

		String remoteAddress = servletRequest.getRemoteAddr();
		ReCaptchaResponse reCaptchaResponse = this.reCaptcha.checkAnswer(
				remoteAddress, challangeField, responseField);

		if (reCaptchaResponse.isValid() && !result.hasErrors()) {
			if (userService.getUserByEmail(user.getEmail()) != null) {
				String newpass = PasswordUtil.getNewPassword();				
				User oUser = userService.getUserByEmail(user.getEmail());
				oUser.setPassword(newpass);
				userService.updateUser(oUser);
				GMailUtil.send(user.getEmail(), "New Password",
						"New password for account: " + user.getEmail() + "\n"
								+ newpass);
				return "redirect:/";
			} else {
				result.rejectValue("email", "username");
				return "reset";
			}
		} else {
			if (!reCaptchaResponse.isValid()) {
				// Captcha Error
				result.addError(new ObjectError("captcha_error",
						"Invalid captcha code!"));
			}
			System.out.println("Validate error!");
			return "reset";
		}
	}
}
